package io.admin.modules.sys.controller;

import io.admin.common.annotation.LogOperation;
import io.admin.common.constant.Constant;
import io.admin.common.page.PageData;
import io.admin.common.utils.ExcelUtils;
import io.admin.common.utils.Result;
import io.admin.common.utils.StringUtils;
import io.admin.common.validator.AssertUtils;
import io.admin.common.validator.ValidatorUtils;
import io.admin.common.validator.group.AddGroup;
import io.admin.common.validator.group.DefaultGroup;
import io.admin.common.validator.group.UpdateGroup;
import io.admin.modules.sys.dto.EquipmentTypeDTO;
import io.admin.modules.sys.dto.LineDTO;
import io.admin.modules.sys.dto.ProjectDTO;
import io.admin.modules.sys.excel.LineExcel;
import io.admin.modules.sys.service.EquipmentService;
import io.admin.modules.sys.service.LineService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jsoup.helper.DataUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 项目线路关系表
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2024-07-06
 */
@RestController
@RequestMapping("sysproject/line")
@Api(tags="项目线路关系表")
public class LineController {
    @Autowired
    private LineService lineService;
    @Autowired
    private EquipmentService equipmentService;


    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
        @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
        @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    public Result<PageData> page(@ApiIgnore @RequestParam Map<String, Object> params){
        PageData page = lineService.page(params);
        return new Result<PageData>().ok(page);
    }

    @GetMapping("{id}")
    @ApiOperation("信息")
    public Result<LineDTO> get(@PathVariable("id") Long id){
        LineDTO data = lineService.get(id);
        return new Result<LineDTO>().ok(data);
    }

    @PostMapping
    @ApiOperation("保存")
    @LogOperation("保存")
    public Result save(@RequestBody LineDTO dto) throws Exception {
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        LineDTO lineDTO =lineService.findLineByParam(dto);
        if(null != lineDTO  ){
            return new Result().error("当前线路名称重复了，请重新修改了在提交");
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        dto.setCreateDate(new Date());
        dto.setStartDate(format.parse(dto.getStartDateStr()));
        lineService.save(dto);
        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @LogOperation("修改")
    public Result update(@RequestBody LineDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
        LineDTO lineDTO =lineService.findLineByParam(dto);
        if(null != lineDTO  ){
            if(!lineDTO.getId().equals(dto.getId())){
                return new Result().error("当前线路名称重复了，请重新修改了在提交");
            }
        }
        lineService.update(dto);

        return new Result();
    }

    @DeleteMapping
    @ApiOperation("删除")
    @LogOperation("删除")
    public Result delete(@RequestBody Long[] ids){
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");
        //判断当前是否有子级有的话不可以删除
        Map<String,Object> map=new HashMap<>(1);
        map.put("lineId",String.valueOf(ids[0]));
        if(equipmentService.list(map).size()==0){
            lineService.delete(ids);
            return new Result();
        }else{
            return new Result().error("该线路下有设备，请先删除设备！");
        }
    }

    @GetMapping("export")
    @ApiOperation("导出")
    @LogOperation("导出")
    public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<LineDTO> list = lineService.list(params);

        ExcelUtils.exportExcelToTarget(response, null, "项目线路关系表", list, LineExcel.class);
    }
    @GetMapping("/getLineByProjectId")
    @LogOperation("根据项目id获取所有线路")
    public Result<List<LineDTO>> getType(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String,Object> param = new HashMap<>(1);
        param.put("projectId",request.getParameter("projectId"));
        List<LineDTO> list = lineService.list(param);
        return new Result<List<LineDTO>>().ok(list);
    }
    @RequestMapping("/findProSelect")
    public Result findProSelect(){
        return new Result<>().ok(lineService.findProSelect());
    }
    @RequestMapping("/findLineSelect")
    public Result findProSelect(HttpServletRequest request,HttpServletResponse response){
        return new Result<>().ok(lineService.findLineSelect(request.getParameter("proId")));
    }
    @RequestMapping("/copyLine")
    public Result copyLine(HttpServletRequest request,HttpServletResponse response){
        String lineId = request.getParameter("lineId");
        String thisProjectId = request.getParameter("thisProjectId");
        lineService.saveCopyLine(lineId,thisProjectId);
        return new Result<>().ok(lineService.findLineSelect(request.getParameter("proId")));
    }

    @RequestMapping("/exportByLineId")
    public Result exportByLineId(HttpServletRequest request,HttpServletResponse response){
        String lineId = request.getParameter("lineIds");
        String zoom = request.getParameter("zoom");
        String imgName = request.getParameter("fileName");
        String fileNameByChart = request.getParameter("fileNameByChart");
        Map<String,Object> excelParam = new HashMap<>();
        excelParam.put("fileNameByChart",fileNameByChart);
        String fileName = lineService.exportByLineId(lineId,zoom,imgName,excelParam);
        if(StringUtils.isBlank(fileName)){
            return new Result<>().error("没有数据");
        }
        Map<String,Object> reData = new HashMap<>();
        reData.put("fileName",fileName);
        return new Result<>().ok(reData);
    }



}